<template>
  <div class="result">
    <div class="container">
      <h1>装机方案</h1>
      
      <!-- 方案类型选择 -->
      <div class="result-type-selector">
        <button 
          class="tab-button" 
          :class="{ active: selectedTab === 'recommended' }"
          @click="selectedTab = 'recommended'"
        >
          推荐方案
        </button>
        <button 
          class="tab-button" 
          :class="{ active: selectedTab === 'saved' }"
          @click="selectedTab = 'saved'"
        >
          已保存方案
        </button>
      </div>

      <!-- 推荐方案内容 -->
      <div v-if="selectedTab === 'recommended'" class="recommended-results">
        <div class="scenario-filters">
          <h2>按使用场景筛选</h2>
          <div class="filter-buttons">
            <button 
              class="filter-btn" 
              :class="{ active: selectedScenario === 'gaming' }"
              @click="selectedScenario = 'gaming'"
            >
              游戏配置
            </button>
            <button 
              class="filter-btn" 
              :class="{ active: selectedScenario === 'workstation' }"
              @click="selectedScenario = 'workstation'"
            >
              工作站配置
            </button>
            <button 
              class="filter-btn" 
              :class="{ active: selectedScenario === 'budget' }"
              @click="selectedScenario = 'budget'"
            >
              经济型配置
            </button>
            <button 
              class="filter-btn" 
              :class="{ active: selectedScenario === 'balanced' }"
              @click="selectedScenario = 'balanced'"
            >
              均衡型配置
            </button>
          </div>
        </div>

        <!-- 预算滑块 -->
        <div class="budget-slider">
          <div class="budget-info">
            <label>预算范围：</label>
            <span>¥{{ budgetRange.min.toLocaleString() }} - ¥{{ budgetRange.max.toLocaleString() }}</span>
          </div>
          <input 
            type="range" 
            min="2000" 
            max="50000" 
            step="1000" 
            v-model="budgetRange.max" 
            @input="generateRecommendations"
          >
        </div>

        <!-- 推荐方案列表 -->
        <div class="recommendations-list">
          <h2>推荐装机方案 ({{ recommendations.length }})</h2>
          <div v-if="isGenerating" class="loading">
            <div class="spinner"></div>
            <p>正在生成推荐方案...</p>
          </div>
          <div v-else-if="recommendations.length === 0" class="empty-state">
            <p>暂无符合条件的推荐方案，请调整预算范围</p>
          </div>
          <div v-else class="recommendations-grid">
            <div v-for="(recommendation, index) in recommendations" :key="index" class="recommendation-card">
              <div class="card-header">
                <h3>{{ recommendation.name }}方案</h3>
                <div class="card-tags">
                  <span class="tag performance">性能评分: {{ recommendation.performanceScore }}</span>
                  <span class="tag price" v-if="isActiveVip">
                    <span class="vip-price">¥{{ getVipPrice(recommendation.totalPrice).toLocaleString() }}</span>
                    <span class="original-price">¥{{ recommendation.totalPrice.toLocaleString() }}</span>
                  </span>
                  <span v-else class="tag price">¥{{ recommendation.totalPrice.toLocaleString() }}</span>
                </div>
              </div>
              <div class="card-body">
                <div class="components-list">
                    <div class="component-item">
                      <span class="component-type">CPU</span>
                      <span class="component-name">{{ recommendation.build.cpu?.name }}</span>
                    </div>
                    <div class="component-item">
                      <span class="component-type">显卡</span>
                      <span class="component-name">{{ recommendation.build.gpu?.name }}</span>
                    </div>
                    <div class="component-item">
                      <span class="component-type">主板</span>
                      <span class="component-name">{{ recommendation.build.motherboard?.name }}</span>
                    </div>
                    <div class="component-item">
                      <span class="component-type">内存</span>
                      <span class="component-name">{{ recommendation.build.ram?.name }}</span>
                    </div>
                    <div class="component-item">
                      <span class="component-type">存储</span>
                      <span class="component-name">{{ recommendation.build.storage?.name }}</span>
                    </div>
                  </div>
              </div>
              <div class="card-footer">
                <button class="btn-primary" @click="loadRecommendation(recommendation)">使用此方案</button>
                <button class="btn-secondary" @click="saveRecommendation(recommendation)">保存方案</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 已保存方案内容 -->
      <div v-if="selectedTab === 'saved'" class="saved-results">
        <h2>我的已保存方案</h2>
        <div v-if="savedConfigurations.length === 0" class="empty-state">
          <p>您还没有保存任何装机方案</p>
          <button class="btn-primary" @click="$router.push('/builder')">开始装机</button>
        </div>
        <div v-else class="saved-configs-grid">
          <div v-for="(config, index) in savedConfigurations" :key="index" class="saved-config-card">
            <div class="card-header">
              <h3>{{ config.name || `方案${index + 1}` }}</h3>
              <div class="card-meta">
                <span>保存于 {{ formatDate(config.savedAt) }}</span>
                <div class="card-actions">
                  <button class="btn-icon" @click="loadSavedConfig(config)">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                      <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"></path>
                    </svg>
                  </button>
                  <button class="btn-icon" @click="deleteSavedConfig(index)">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                      <path d="M3 6h18"></path>
                      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="components-list">
                  <div v-for="(item, index) in Object.entries(config.components)" :key="index">
                    <div v-if="item[1]" class="component-item">
                      <span class="component-type">{{ getComponentTypeName(item[0]) }}</span>
                      <span class="component-name">{{ item[1].name }}</span>
                    </div>
                  </div>
                </div>
              <div class="config-summary">
                <span v-if="isActiveVip">
                  总价：<span class="vip-price">¥{{ getVipPrice(config.totalPrice).toLocaleString() }}</span>
                  <span class="original-price">¥{{ config.totalPrice.toLocaleString() }}</span>
                </span>
                <span v-else>总价：¥{{ config.totalPrice.toLocaleString() }}</span>
                <span>性能评分：{{ config.performanceScore }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import type { PCBuild, Recommendation } from '../types/components';
import type { User, VipInfo } from '../types/vip';
import { recommendationSystem } from '../utils/recommendationSystem';
import { getUserWithVipInfo, isVipActive, calculateVipPrice } from '../utils/vipService';

const router = useRouter();

// 选中的标签页
const selectedTab = ref<'recommended' | 'saved'>('recommended');

// 选中的场景
const selectedScenario = ref<'gaming' | 'workstation' | 'budget' | 'balanced'>('balanced');

// 预算范围
const budgetRange = ref({
  min: 2000,
  max: 15000
});

// 推荐方案
const recommendations = ref<Recommendation[]>([]);

// 已保存的配置
const savedConfigurations = ref<({
  components: PCBuild;
  savedAt: Date;
  totalPrice: number;
  performanceScore: number;
  name?: string;
})[]>([]);

// 用户信息
const user = ref<User | null>(null);

// 是否正在生成推荐方案
const isGenerating = ref(false);

// 加载用户信息
const loadUserInfo = () => {
  user.value = getUserWithVipInfo();
};

// 检查是否为活跃VIP用户
const isActiveVip = computed(() => {
  return isVipActive(user.value?.vipInfo);
});

// 计算VIP折扣价的函数
const getVipPrice = (price: number) => {
  if (!isActiveVip.value) return price;
  return calculateVipPrice(price, user.value?.vipInfo);
};

// 计算方案总价（考虑VIP折扣）
const calculateBuildPrice = (components: PCBuild) => {
  const originalTotal = Object.values(components).reduce((sum, component) => {
    if (!component) return sum;
    return sum + (component.price || 0);
  }, 0);
  return calculateVipPrice(originalTotal, user.value?.vipInfo, true); // true表示整机折扣
};

// 计算节省金额的函数
const getSavings = (price: number) => {
  if (!isActiveVip.value) return 0;
  return price - getVipPrice(price);
};

// 生命周期钩子
onMounted(() => {
  loadUserInfo();
  
  // 监听localStorage变化
  window.addEventListener('storage', (event) => {
    if (event.key === 'user' || event.key === 'vipInfo') {
      loadUserInfo();
    }
  });
});

// 场景名称映射
const getScenarioName = (scenario: string): string => {
  const scenarioNames: Record<string, string> = {
    gaming: '游戏',
    workstation: '工作站',
    budget: '经济型',
    balanced: '均衡型'
  };
  return scenarioNames[scenario] || scenario;
};

// 配件类型名称映射
const getComponentTypeName = (type: string): string => {
  const typeNames: Record<string, string> = {
    cpu: 'CPU',
    gpu: '显卡',
    ram: '内存',
    motherboard: '主板',
    storage: '存储',
    powerSupply: '电源',
    pcCase: '机箱',
    cpuCooler: 'CPU散热器'
  };
  return typeNames[type] || type;
};

// 格式化日期
const formatDate = (date: Date): string => {
  const d = new Date(date);
  return d.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 生成推荐方案
const generateRecommendations = () => {
  isGenerating.value = true;
  
  // 模拟异步生成推荐方案
  setTimeout(() => {
    recommendations.value = recommendationSystem.generateRecommendations(
      budgetRange.value.max,
      selectedScenario.value
    );
    isGenerating.value = false;
  }, 800);
};

// 加载推荐方案到装机页面
const loadRecommendation = (recommendation: Recommendation) => {
  // 将推荐方案保存到sessionStorage，然后跳转到装机页面
  sessionStorage.setItem('preloadedBuild', JSON.stringify(recommendation.build));
  router.push('/builder');
};

// 保存推荐方案
const saveRecommendation = (recommendation: Recommendation) => {
  const config = {
    components: recommendation.build,
    savedAt: new Date(),
    totalPrice: recommendation.totalPrice,
    performanceScore: recommendation.performanceScore
  };
  
  savedConfigurations.value.push(config);
  saveConfigurationsToStorage();
  
  // 显示保存成功提示
  alert('方案已保存！');
};

// 加载保存的配置
const loadSavedConfig = (config: {
  components: PCBuild;
  savedAt: Date;
  totalPrice: number;
  performanceScore: number;
}) => {
  // 将保存的配置保存到sessionStorage，然后跳转到装机页面
  sessionStorage.setItem('preloadedBuild', JSON.stringify(config.components));
  router.push('/builder');
};

// 删除保存的配置
const deleteSavedConfig = (index: number) => {
  if (confirm('确定要删除这个方案吗？')) {
    savedConfigurations.value.splice(index, 1);
    saveConfigurationsToStorage();
  }
};

// 保存配置到本地存储
const saveConfigurationsToStorage = () => {
  localStorage.setItem('savedConfigurations', JSON.stringify(savedConfigurations.value));
};

// 从本地存储加载配置
const loadConfigurationsFromStorage = () => {
  const saved = localStorage.getItem('savedConfigurations');
  if (saved) {
    try {
      savedConfigurations.value = JSON.parse(saved);
      // 转换日期字符串为Date对象
      savedConfigurations.value.forEach(config => {
        config.savedAt = new Date(config.savedAt);
      });
    } catch (error) {
      console.error('Failed to load saved configurations:', error);
    }
  }
};

// 初始化
const init = () => {
  loadConfigurationsFromStorage();
  generateRecommendations();
};

// 监听场景和预算变化
const scenarioWatcher = computed(() => selectedScenario.value);
const budgetWatcher = computed(() => budgetRange.value.max);

// 当场景或预算变化时，重新生成推荐方案
scenarioWatcher.value; // 触发计算
budgetWatcher.value; // 触发计算

// 执行初始化
init();
</script>

<style scoped>
.result {
  padding: 3rem 0;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1.5rem;
}

.result h1 {
  text-align: center;
  font-size: 2.5rem;
  margin: 0 0 2rem 0;
  color: #1a1a1a;
}

/* 标签页选择器 */
.result-type-selector {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-bottom: 2rem;
}

.tab-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 4px;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: white;
  color: #666;
  border: 2px solid #ddd;
}

.tab-button:hover {
  background-color: #f9f9f9;
  transform: translateY(-2px);
}

.tab-button.active {
  background-color: #00ccff;
  color: #1a1a1a;
  border-color: #00ccff;
}

/* 场景筛选器 */
.scenario-filters {
  background-color: white;
  border-radius: 10px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.scenario-filters h2 {
  margin: 0 0 1rem 0;
  color: #1a1a1a;
  font-size: 1.3rem;
}

.filter-buttons {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 0.75rem 1.5rem;
  border: 2px solid #ddd;
  border-radius: 4px;
  background-color: white;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
}

.filter-btn:hover {
  background-color: #f9f9f9;
  transform: translateY(-2px);
}

.filter-btn.active {
  background-color: #00ccff;
  color: #1a1a1a;
  border-color: #00ccff;
}

/* 预算滑块 */
.budget-slider {
  background-color: white;
  border-radius: 10px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.budget-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.budget-info label {
  font-weight: bold;
  color: #1a1a1a;
}

.budget-info span {
  color: #00ccff;
  font-weight: bold;
}

.budget-slider input[type="range"] {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  -webkit-appearance: none;
}

.budget-slider input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #00ccff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.budget-slider input[type="range"]::-webkit-slider-thumb:hover {
  transform: scale(1.2);
}

/* 推荐方案列表 */
.recommendations-list {
  background-color: white;
  border-radius: 10px;
  padding: 1.5rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.recommendations-list h2 {
  margin: 0 0 2rem 0;
  color: #1a1a1a;
  font-size: 1.5rem;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 3rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #00ccff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 3rem;
  color: #666;
}

/* 推荐方案网格 */
.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 1.5rem;
}

.saved-configs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 1.5rem;
}

/* 推荐方案卡片 */
.recommendation-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.recommendation-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.saved-config-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.saved-config-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  background-color: #00ccff;
  color: #1a1a1a;
  padding: 1rem;
  position: relative;
}

.card-header h3 {
  margin: 0;
  font-size: 1.2rem;
}

.card-tags {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.tag {
  padding: 0.25rem 0.75rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
  background-color: rgba(255, 255, 255, 0.2);
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.5rem;
  font-size: 0.9rem;
}

.card-actions {
  display: flex;
  gap: 0.5rem;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.25rem;
  color: #1a1a1a;
  transition: all 0.3s ease;
  border-radius: 4px;
}

.btn-icon:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.card-body {
  padding: 1rem;
}

.card-body .components-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  background-color: white;
  border-radius: 4px;
}

.component-type {
  background-color: #00ccff;
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
  margin-right: 1rem;
  min-width: 60px;
  text-align: center;
}

.component-name {
  flex: 1;
  color: #1a1a1a;
  font-size: 0.9rem;
}

.config-summary {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  color: #1a1a1a;
}

/* VIP价格显示 */
.vip-price {
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 0.3rem;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 0.9rem;
}

.tag.price {
  display: inline-flex;
  align-items: center;
}

.card-footer {
  padding: 1rem;
  background-color: white;
  display: flex;
  gap: 1rem;
}

/* 按钮样式 */
.btn-primary, .btn-secondary {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-block;
  text-align: center;
  flex: 1;
}

.btn-primary {
  background-color: #00ccff;
  color: #1a1a1a;
}

.btn-primary:hover {
  background-color: #00a3cc;
  transform: translateY(-2px);
}

.btn-secondary {
  background-color: transparent;
  color: #00ccff;
  border: 2px solid #00ccff;
}

.btn-secondary:hover {
  background-color: #00ccff;
  color: #1a1a1a;
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result h1 {
    font-size: 2rem;
  }
  
  .result-type-selector {
    flex-direction: column;
    align-items: center;
  }
  
  .tab-button {
    width: 100%;
    max-width: 300px;
  }
  
  .filter-buttons {
    justify-content: center;
  }
  
  .recommendations-grid, .saved-configs-grid {
    grid-template-columns: 1fr;
  }
  
  .card-footer {
    flex-direction: column;
  }
  
  .btn-primary, .btn-secondary {
    width: 100%;
  }
}
</style>